﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using Budgeter.Models;

namespace Budgeter.Extensions
{
    public static class Extensions
    {
        public static IList<T> ToMinimumLengthArray<T>(this IEnumerable<T> e, int minimumLength, Func<T> instantiator)
        {
            //int count = 0;
            //foreach (T item in e)
            //{
            //    yield return item;
            //    count++;
            //}
            //if (count >= padTo)
            //    yield break;
            //while (count < padTo)
            //    yield return instantiator();

            var list = e.ToList();
            if (list.Count >= minimumLength)
            {
                return list;
            }
            else
            {
                int diff = minimumLength - list.Count;
                IList<T> newItems = new List<T>();
                while (diff-- > 0)
                    newItems.Add(instantiator());
                return list.Concat(newItems).ToList();
            }
        }

        public static Models.EntryType GetByCategoryAndName(this IEnumerable<Models.EntryType> self, string category, string name)
        {
            return (from i in self
                    where i.Category.Equals(category) && i.Name.Equals(name)
                    select i).First();
        }

        public static Models.Interval GetByAbbreviation(this IEnumerable<Models.Interval> self, string abbreviation)
        {
            return (from i in self
                    where i.Abbreviation.Equals(abbreviation)
                    select i).First();
        }

        public static void RemoveRange<TEntity>(this DbSet<TEntity> self, IEnumerable<TEntity> items) where TEntity : class
        {
            foreach (var i in items.ToArray())
                self.Remove(i);
        }

        public static Models.Budget FindByReceiptNumber(this IEnumerable<Models.Budget> self, int receiptNumber)
        {
            return self.First(x => x.ReceiptNumber == receiptNumber);
        }

        public static decimal GetFortnightlyEquivalent(this Models.Entry self)
        {
            return ((decimal)((float)self.Amount / self.Interval.YearEquivalent)) / 26;
        }

        public static decimal GetFortnightlyIncome(this Models.Budget self)
        {
            return self.Entries.Where(x => x.EntryType.IsIncome).Sum(x => x.GetFortnightlyEquivalent());
        }

        public static decimal GetFortnightlyExpense(this Models.Budget self)
        {
            return self.Entries.Where(x => !x.EntryType.IsIncome).Sum(x => x.GetFortnightlyEquivalent());
        }
    
    }
}